/// <reference path="typings/tsd.d.ts" />

class PlayAudio {
    private el: Element;
    private audios: Array<string>;

    constructor(element:Element) {
        this.el = element;
        this.audios = [];
    }

    putAudios(element: Element) {
        let srcs = element.getAttribute('data-src');
        srcs.split('|').forEach((audio) => {
            this.audios.push(audio);
        });
    }

    choiceAudioType(src) {
        if (src.match(/\.(mp3)$/)) {
            return 'audio/mpeg';
        }
        if (src.match(/\.(ogg)$/)) {
            return 'audio/ogg';
        }
        return 'audio/mpeg';
    }

    createAudioEl() {
        let audioEl = document.createElement('audio');
        this.audios.forEach((audio) => {
            let sourceEl = document.createElement('source');
            sourceEl.setAttribute('src', audio);
            sourceEl.setAttribute('type', this.choiceAudioType(audio));
            audioEl.appendChild(sourceEl);
        });
        audioEl.load();
        return audioEl;
    }

    render(wrapper: Element) {
        this.putAudios(this.el);
        let audio = this.createAudioEl();
        wrapper.appendChild(audio);
        this.el.addEventListener('click', () => {
            audio.currentTime = 0;
            audio.play();
        });
    }
}

document.addEventListener('DOMContentLoaded', function () {
    jQuery('body').find('[data-action="play.audio"]').each((i, el) => {
        let playAudio = new PlayAudio(el);
        playAudio.render(document.getElementsByTagName('body')[0]);
    });
});